[Java] 使用DateTimeFormatterBuilder 解析日期字串


Posted by yaweichiang on 2022-11-26

在後端呼叫第三方API時取得的日期時間字串格式如下:/Date(xxxxxxxxxxxxx+xxxx)/
需要將日期時間字串轉換成以下格式:yyyy-MM-ddTHH:mm:ss

使用DateTimeFormatterBuilder建立符合原始字串的Formatter,用來將原始字串parse成相應LocalDateTime物件
再將LocalDateTime物件透過目標格式的Formatter格式化成我們所想要的日期時間格式字串

DateTimeFormatter jsonDateTimeFormatter = new DateTimeFormatterBuilder()
                .appendLiteral("/Date(")
                .appendValue(ChronoField.INSTANT_SECONDS)
                .appendValue(ChronoField.MILLI_OF_SECOND,3)
                .appendOffset("+HHmm","+0000")
                .appendLiteral(")/")
                .toFormatter();

DateTimeFormatter targetDateTimeFormatter = DateTiemFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
@JsonProperty("startDate")
private String startDate;

public void setStartDate(String startDate){
    if(startDate.matches("^\\/Date\\(\\d{13,13}\\+\\d{4,4}\\)\\/$")){
        LocalDatetime dateTime = LocalDateTime.parse(startDate,jsonDateTimeFormatter);
        startDate = dateTime.format(targetDateTimeFormatter);
    }
    this.startDate = startDate;
}

#java #DateTimeFormat #JsonDate







Related Posts

使用 TensorFlow 來做簡單的手寫數字辨識

使用 TensorFlow 來做簡單的手寫數字辨識

使用 Terraform 在 GCP 上建立外部和內部的全球 IP 地址

使用 Terraform 在 GCP 上建立外部和內部的全球 IP 地址

Ubuntu 對調左側 ctrl 鍵與大寫鍵的 keycode

Ubuntu 對調左側 ctrl 鍵與大寫鍵的 keycode


Comments